#ifndef Scenic_Renderer_Resource_h
#define Scenic_Renderer_Resource_h


#include <jni.h>

#include "DynArray.h"


namespace Scenic
{
namespace Renderer
{
	
class CriticalSection
{
#ifdef WIN32
	CRITICAL_SECTION criticalSection;
#else
	pthread_mutex_t mutex;
#endif
	int lockCount;
public:
	CriticalSection();
	virtual ~CriticalSection();

	int enterCriticalSection();
	int leaveCriticalSection();
	
	virtual void onEnter();
	virtual void onLeave();
};

class Synchronized
{
	CriticalSection *criticalSection;
public:
	Synchronized(CriticalSection *criticalSection) 
	{ 
		this->criticalSection = criticalSection;
		this->criticalSection->enterCriticalSection(); 
	}
	Synchronized(CriticalSection &criticalSection) 
	{ 
		this->criticalSection = &criticalSection;
		this->criticalSection->enterCriticalSection(); 
	}
	~Synchronized()
	{
		criticalSection->leaveCriticalSection();
	}
};

class Resource;

class ResourcePool : public CriticalSection
{
public:
	DynArray<Resource*> pool;
	int size;

public:
	ResourcePool();

	Resource *get(int id);
	DynArray<Resource*> &getAll() { return pool; }
	void add(Resource *resource);
	void remove(Resource *resource);

};

class JNIEnvPtr
{
	JavaVM *vm;
	bool detach;
	JNIEnv *env;
public:

	JNIEnvPtr(JavaVM *vm);
	~JNIEnvPtr();

	JNIEnv *getEnv() { return env; }
	JNIEnv *operator->() { return env; }
};

class Resource : public CriticalSection
{
	int debug;
	int refCount;
	JavaVM *javaVm;
	jobject javaObject;
	int javaObjectRefCount;
public:
	int id;
	ResourcePool *pool;

	Resource(ResourcePool *pool);
	virtual ~Resource();

	void addRef() { refCount++; }
	void release();

	jobject getJavaObject() { return javaObject; }
	JavaVM *getJavaVM() { return javaVm; }
	void addReference(JNIEnv *env, jobject localObject);
	void addReference(JavaVM *vm, jobject localObject);
	void releaseReference();
};

}
}

#endif
